<template>
  <div class="g-inherit m-main p-session">
    <NavBar
    :unreadList="unreadList"
    @setActiveItem = "getActiveItem"
    :isDoctorSessionActive = "isDoctorSessionActive"
    >
    </NavBar>
    <div class="sessionList-box">
      <van-cell-group class="u-list">
      <!-- 如果是全部页面，还要添加一个过滤查询 -->
      <div class="search-box" v-show="isDoctorSessionActive===3&&sessionlist.length>0">
        <i class="iconfont icon-search" v-show="!closeShow"></i>
        <input type="text" v-model="filterSessionlist" placeholder="请输入患者姓名" @focus="searchClose"/>
        <i class="iconfont icon-close" v-show="closeShow" @click="deleteFilteWord"></i>
      </div>
        <van-cell
          v-for="session in sessionlist "
          class="u-list-item"
          :inline-desc="session.lastMsgShow"
          :key="session.chatGroupId"
          :sessionId="session.id"
          @click.native="enterChat(session)"
          >
          <template slot="title">
            <div class="left-dot" :class="{unread: session.unread > 0}"></div>
            <div class="patientMsg-box">
              <div class="name">{{session.custom.name}}</div>
              <div class="alert" style="float:right;margin-right:-10px;position:absolute;right:0;margin-right:20px;top:10px;">医生：{{session.doctorId}}</div>
              <div class="alert"><span>{{session.custom.sex==='1'?'男':'女'}}</span><span>{{session.custom.age}}</span></div>
              <div class="alert" v-show="session.custom.diseaseDesc"><span>病情:</span>{{session.custom.diseaseDesc |splitMsg}}</div>
              <div class="alert" v-if="session.lastMsgShow">
                <span>对话:</span>
                {{session.lastMsgShow | splitMsg}}
                <span class="session-time">
                  {{session.lastTimeShow}}
                </span>
              </div>
              <div class="alert" v-else>历史数据正在加载中...</div>
              <!-- <div class="lastMsg">对话：{{session.lastMsgShow | splitMsg}}<span v-show="session.lastMsgShow.length>10">...</span></div> -->
            </div>
          </template>
          <span
            class="u-tag-del"
            :class="{active: delSessionId===session.id}"
            @click="deleteSession"
            ></span>
        </van-cell>
      </van-cell-group>
    </div>
    <!-- 没有更多消息 -->
    <div class="nomorelist" v-show="sessionlist.length===0">没有更多消息</div>
  </div>
</template>

<script>
import util from '../../utils'
import cookie from '../../utils/cookie'
import config from '../../configs'
import { getDoctorSessionList, endNewTalk, gotoConnectTalk} from '@/api/dialog'
import NavBar from '@/views/components/NavBar'
export default {
  components : { NavBar },
  // 获取患者信息
  created () {

    getDoctorSessionList(this.userid).then(res => {
      // 将获得的患者sessionlist保存到store里面
      this.ownsessionlist = JSON.parse(res.data.data)
      // 遍历从数据库拿到的数据
      this.ownsessionlist.forEach(ownitem => {
      // 数据格式化部分医生的信息
        ownitem.custom = ownitem.custom ? JSON.parse(ownitem.custom) : ''
        ownitem.icon = ownitem.icon || this.doctorImg
      })

      let listData1 = 0,
        listData2 = 0

      this.ownsessionlist.map(item => {
        if (item.custom.isNew == '1' && item.isEnd == '0'){
          listData1 ++
        }
        if (item.custom.isNew == '0' && item.isEnd == '0'){
          listData2 ++
        }
      })
      if(listData1>0) {
        this.isDoctorSessionActive = 1
      }else if (listData2>0) {
        this.isDoctorSessionActive = 2
      }else {
        this.isDoctorSessionActive = 3
      }
    })


    // 这儿需要先接受到网易云信推送的列表，如果列表里面数据存在
    // 从列表里面获取数据后保存到store里面 store.state.subscribeList
    let sublist = []
    this.$store.state.teamlist.forEach(item => {
      sublist.push(item.owner)
    })
    this.$store.commit('updateSubscribeList',sublist)
  },

  data () {
    return {
      delSessionId: null,
      stopBubble: false,
      noticeIcon: config.noticeIcon,
      myPhoneIcon: config.myPhoneIcon,
      myGroupIcon: config.defaultGroupIcon,
      myAdvancedIcon: config.defaultAdvancedIcon,
      // 存放从公司服务器上获取的医生列表信息
      sessionAddList: [],
      msg: {},
      // 属于哪个列表
      isDoctorSessionActive: Number,
      // isNomoreShow: false,
      // 需要展示的数据
      showsessionlist: [],
      ownsessionlist: [],
      nomorelist: false,
      filterSessionlist: '',
      // 搜索框里面的叉
      closeShow: false
    }
  },
  computed : {
    userid () {
      let userid = this.$route.query.userid
      return userid
    },
    sysMsgUnread () {
      let temp = this.$store.state.sysMsgUnread
      let sysMsgUnread = temp.addFriend || 0
      sysMsgUnread += temp.team || 0
      let customSysMsgUnread = this.$store.state.customSysMsgUnread
      return sysMsgUnread + customSysMsgUnread
    },
    userInfos () {
      return this.$store.state.userInfos
    },
    myInfo () {
      return this.$store.state.myInfo
    },
    myPhoneId () {
      return `${this.$store.state.userUID}`
    },
    sessionlist () {
      let sessionlist = this.$store.state.sessionlist
      let ownsessionlist =this.ownsessionlist
      ownsessionlist.forEach(ownitem => {
        // 遍历从网易拿到的sessionlist，将相关字段拼接到ownsessionlist里面
        sessionlist.forEach(sessionitem => {
          // 处理最后一条信息
          let lastMsg = sessionitem.lastMsg || {}
          if (lastMsg.type === 'text') {
            sessionitem.lastMsgShow = lastMsg.text || ''
          } else if (lastMsg.type === 'custom') {
            sessionitem.lastMsgShow = util.parseCustomMsg(lastMsg)
          } else if (lastMsg.scene === 'team' && lastMsg.type === 'notification') {
            sessionitem.lastMsgShow = util.generateTeamSysmMsg(lastMsg)
          } else if (util.mapMsgType(lastMsg)) {
            sessionitem.lastMsgShow = `[${util.mapMsgType(lastMsg)}]`
          } else {
            sessionitem.lastMsgShow = ''
          }
          if (sessionitem.lastMsg.time) {
            sessionitem.lastTimeShow = util.formatDate(sessionitem.lastMsg.time, true)
          }
          // 拼接对象
          if(sessionitem.to === ownitem.chatGroupId) {
            ownitem = Object.assign(ownitem,sessionitem)
          }
        })
      })
      let showSessionlist = ownsessionlist.filter(item => {
        if(this.isDoctorSessionActive === 1){
           if (item.custom.isNew == '1' && item.isEnd == '0'){
             return true
           }
        } else if (this.isDoctorSessionActive ==2){
          if (item.custom.isNew == '0' && item.isEnd == '0'){
            return true
          }
        } else if (this.isDoctorSessionActive == 3){
          // if (item.isEnd == '1')
            return true
        }
      })
      // 用来搜索过滤
      let filtersession = showSessionlist.filter(item => {
        let name = item.custom.name || ' '
        if(name.indexOf(this.filterSessionlist)>-1){
          return true
        }
      })
      if(filtersession.length===0){
        return showSessionlist
      }else{
        return filtersession
      }
      // return filtersession
    },
    // 用来判断未读的数量
    // 主要分为新对话和对话中两种情况
    // 将新对话栏目中存在未读消息的列表加起来的综合就是新对话的未读数量
    // 将对话中栏目中存在未读消息的列表加起来的综合就是对话中的未读数量
    unreadList () {
      let list = {newNumber:0,connetNumber:0,allNumber:0}
      this.sessionlist.forEach (item => {
        if (this.isDoctorSessionActive == 1) {
          list.newNumber += item.unread
        }
        if (this.isDoctorSessionActive === 2) {
          list.connetNumber += item.unread
        }
        if (this.isDoctorSessionActive ===3) {
          list.allNumber += item.unread
        }
      })
      return list
    },
    canLoadMore () {
      return !this.$store.state.noMoreHistoryMsgs
    },
    // 获取未读消息的数量
    unreadAccounts() {
      return this.$store.state.teamMsgReadsDetail.unreadAccounts
    },
    doctorInfo () {
     let doctorInfo = this.$store.state.dUserInfo
     return doctorInfo
    }
  },
  methods: {
    enterSysMsgs () {
      if (this.hideDelBtn())
        return
      location.href = '/sysmsgs'
    },
    enterChat (session) {
      let doctorInfo = this.doctorInfo
      let fromImId = doctorInfo.imUserId
      let fromId = doctorInfo.userid
      let userid = doctorInfo.userid
      let sessionId = "team-" + session.chatGroupId
      let chatGroupId = session.chatGroupId
      let doctorId = session.doctorId
      let patienterId = session.patienterId
      let customParam = {
            toImId:chatGroupId,
            fromImId:fromImId,
            fromId:fromId,
            to:patienterId
          }
      // 获得药品分享参数，更新到store里面
        // 以后的药品分享页面，会使用到这些参数
      window.sessionStorage.setItem('drugShareParam',JSON.stringify(customParam))
      this.$store.commit('updateDrugShareParam', customParam)
      if (this.hideDelBtn())
        return
      if (session && sessionId){
				// 判断聊天是新患者，就进入对话中
        if(session.isEnd == '0' && session.custom.isNew == '1') {
          endNewTalk(chatGroupId, userid).then(()=>{
					})
					// 如果是全部中，就进入对话中
        }else if(session.isEnd ==1) {
					gotoConnectTalk(chatGroupId, userid).then(()=>{

					})
				}
        this.$router.push({
          path:`/doctorAidChat/${sessionId}`,
          query:{
            sessionName:session.custom.name,
            isDoctorSessionActive: this.isDoctorSessionActive,
            doctorId,
            // patienterId
          }
        })
      }

    },
    // enterMyChat () {
    //   // 我的手机页面
    //   location.href = `#/chat/p2p-${this.myPhoneId}`
    // },
    deleteSession () {
      if (this.delSessionId !== null) {
        this.$store.dispatch('deleteSession', this.delSessionId)
      }
    },
    showDelBtn (vNode) {
      if (vNode && vNode.data && vNode.data.attrs) {
        this.delSessionId = vNode.data.attrs.sessionId
        this.stopBubble = true
        setTimeout(() => {
          this.stopBubble = false
        }, 20)
      }
    },
    hideDelBtn () {
      if (this.delSessionId !== null && !this.stopBubble) {
        // 用于判断是否前置状态是显示删除按钮
        this.delSessionId = null
        return true
      }
      return false
    },
    // 绑定用navbar获取的事件
    getActiveItem (param) {
      this.isDoctorSessionActive = param
    },
     // 获得我需要的数据列表
    getSessionlist () {
      // 获取网易云信服务器的数据
      // let sessionlist = this.jsessionlist
      // let teamlist = this.$store.state.teamlist
      let sessionlist = this.$store.state.sessionlist
        sessionlist.forEach(item =>{
          if (item.lastMsg.time) {
            item.lastMsg.time = util.formatDate(item.lastMsg.time,true)
          }
        })
      // 获取数据
      // 获取openid，来获取患者的sessionlist
      // let userid= this.$store.state.dUserInfo.userid
      getDoctorSessionList(this.userid).then(res => {
      //   // 将获得的患者sessionlist保存到store里面
        let ownsessionlist = JSON.parse(res.data.data)
        // 将会话列表保存起来，用来查询owner，发送离线消息的参数
        this.$store.commit('dateOwnsessionlist',ownsessionlist)
        // 遍历从数据库拿到的数据
        ownsessionlist.forEach( ownitem => {
        // 数据格式化部分患者的信息
        if(ownitem.custom) {
          ownitem.custom = JSON.parse(ownitem.custom)

        }
          // 遍历从网易拿到的sessionlist，将相关字段拼接到ownsessionlist里面
          sessionlist.forEach(sessionitem => {
            if(sessionitem.to === ownitem.chatGroupId) {
              ownitem = Object.assign(ownitem,sessionitem)
            }
          })
        })
          this.showsessionlist = ownsessionlist
        // 获取监听患者的列表
        var sublist = []
        for (var i =0; i< ownsessionlist.length; i++){
          sublist[i] = ownsessionlist[i].patienterId
          // sublist.push(ownsessionlist[i])
        }
        this.$store.commit('updateSubscribeList',sublist)
      })
    },
    searchClose () {
      this.closeShow = true
    },
    deleteFilteWord () {
      this.filterSessionlist = ''
      this.closeShow = !this.closeShow
    }

  },
  filters: {
    // 将最后一条消息进行裁剪
    splitMsg (msg) {
      if(msg && msg.toString().length> 8)
        return msg.toString().substr(0,8) + '...'
      else
        return msg
    },
    // 对显示数据进行过滤
    filterLists (sessionlist) {
      return true
      // sessionlist.filter(item=> {
      //   let name = item.custom.name
      //   if(this.filterSessionlist.indexOf(name)>-1){
      //     return true
      //   }
      // })
    }
  }
}
</script>

<style type="text/css" lang="stylus">
  .p-session
    .sessionList-box
      margin-top: 60px
    .vux-cell-primary
      max-width: 70%
    &.m-main
      background: #f1f1f1
    .u-list
      margin-top: -60px
      background: #f1f1f1
      -webkit-box-align: top
      align-items: top
      .u-list-item
        background: #fff
        min-height: 3rem
        // padding-bottom: 1rem
        .van-cell__title
          color: #333
          line-height: 24px
          display: flex
          .left-dot
            width:9px
            height:9px
            background: #868686
            margin-top: 10px
            border-radius: 50%
					.unread
            background: red!important
          .patientMsg-box
            flex: 1
            margin-left: 6px
            width: 100%
            .name
              font-size: 19px
            .alert
              font-size: 17px
              span
                color: #777
                margin-right: 10px
              .session-time
                position: absolute
                right: 0
                margin-right: 20px
                color: #777
                font-size: 15px
  .nomorelist
    width: 100%
    text-align: center
    margin-top: 50px
    color: #777
  .search-box
    width: 100%
    line-height:40px
    padding: 10px
    background:#fff
    box-sizing:border-box
    display: flex
    border-bottom: 1px solid #f0f0f0
    input
      width:100%
      line-height:40px
      border:none
      font-size: 15px
      flex: 1
      text-align: left
    .iconfont
      width: 30px
      font-size: 16px
      line-height: 40px
      display: block
      top: 10px
      color: #666
      text-align:center
    .icon-search
      color: #999
</style>
